/*
 * Created by JFormDesigner on Sat Aug 25 11:33:32 EDT 2007
 */

package org.timeticker.gui;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
import javax.swing.border.*;
import org.jdesktop.swingx.calendar.*;
import org.timeticker.*;
import org.apache.log4j.Logger;

/**
 * Application main window
 *
 * @author Ivan Latysh
 */
public class MainWindow extends JFrame implements TimekeeperActivityListListener {

  /** Component logger */
  protected Logger logger = Logger.getLogger(this.getClass().getName());
  // load activity action
  private LoadActivitiesAction loadActivitiesAction = new LoadActivitiesAction();

  public MainWindow() {
    preInit();
    initComponents();
    postInit();
  }

  private void preInit(){
    // attach to TimeTicker
    Timekeeper.getInstance().addListener(this);
    // set preferred size TODO preserve window size and position after restart
    this.setPreferredSize(new Dimension(800, 600));
  }

  private void postInit() {
    // create new activity list panel
    ActivityListPanel activityListPanel = new ActivityListPanel(this);
    // add activity list
    mainTabbedPane.add(activityListPanel);

    // decorate monthView TODO refactor into parameters
    monthView.setFirstDayOfWeek(Calendar.SUNDAY);
    // make flagged days with green
    monthView.setFlaggedDayForeground(Color.GREEN);    

    // set activities tab title
    loadedActivityList(Timekeeper.getInstance().getActivityList());
    // load known worked days
    savedActivityList(Timekeeper.getInstance().getActivityList());

    // construct language menu TODO implement discovery of available locales
    ResourceBundle rb = ResourceBundle.getBundle("org.timeticker.timeticker");
    JRadioButtonMenuItem englishMenuItem = new JRadioButtonMenuItem(rb.getString("Language.English"));
    englishMenuItem.setActionCommand("english");
    englishMenuItem.addActionListener(languageActionListener);

    JRadioButtonMenuItem frenchMenuItem = new JRadioButtonMenuItem(rb.getString("Language.French"));
    frenchMenuItem.setActionCommand("french");
    frenchMenuItem.addActionListener(languageActionListener);
    languageMenu.add(englishMenuItem);
    languageMenu.add(frenchMenuItem);

    // select current locale
    if (Locale.getDefault()==Locale.FRENCH) {
      frenchMenuItem.setSelected(true);
    } else {
      englishMenuItem.setSelected(true);
    }

    ButtonGroup bg = new ButtonGroup();
    bg.add(englishMenuItem);
    bg.add(frenchMenuItem);
  }

  /**
   * Set activity tab title when activities reload
   *
   * @param activities just loaded activities
   */
  public void loadedActivityList(ActivityList activities) {
    //todo move date format into config
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String title = (activities.getDateRange().getFrom()==activities.getDateRange().getTo()
            ?dateFormat.format(activities.getDateRange().getFrom())
            :dateFormat.format(activities.getDateRange().getFrom())+" - "+dateFormat.format(activities.getDateRange().getTo())
    );
    mainTabbedPane.setTitleAt(0, title);
  }

  /**
   * Refresh known worked days list
   *
   * @param activities saved actities
   */
  public void savedActivityList(ActivityList activities) {
    // mark known worked days
    long[] dates = Timekeeper.getInstance().getKnownWorkedDays();
    monthView.setFlaggedDates(dates);
  }

  private void thisWindowClosing(WindowEvent e) {
    // invoke close application action
    closeAppAction.actionPerformed(null);
  }

  private void monthViewActionPerformed(ActionEvent e) {
    if ("selectionChanged".equals(e.getActionCommand())) {
      loadActivitiesAction.actionPerformed(e);
    }
  }

  /**
   * Language action listener. Switch locale when another language selected
   */
  private ActionListener languageActionListener = new ActionListener(){
    public void actionPerformed(ActionEvent e) {
      // @TODO implement proper locale switch
      String language = e.getActionCommand();
      if ("french".equals(language)) {
        Locale.setDefault(Locale.FRENCH);
      } else {
        Locale.setDefault(Locale.ENGLISH);
      }
      // update UI
      // hide main window
      MainWindow.this.setVisible(false);
      // detach form TimeTicker
      Timekeeper.getInstance().removeListener(MainWindow.this);
      // destroy main window
      Main.main.destroyMainWindow();      
      // create a new main window
      Main.main.createMainWindow();
    }
  };

  /**
   * Highlight known worked days in the calendar
   */
  private void setKnownWorkedDays() {

  }

  /**
   * Show main window if it is hidden
   */
  public void showWindow() {
    setExtendedState(Frame.NORMAL);
    setVisible(true);
  }

  /**
   * Show main window if it is hidden
   */
  public void hideWindow() {
    setVisible(false);
  }

  private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		// Generated using JFormDesigner Evaluation license - Ivan Latysh
		ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");
		menuBar1 = new JMenuBar();
		timeTickerMenu = new JMenu();
		closeAppMenuItem = new JMenuItem();
		viewMenu = new JMenu();
		languageMenu = new JMenu();
		projectsMenuItem = new JMenuItem();
		workTypesMenuItem = new JMenuItem();
		menuItem3 = new JMenuItem();
		helpMenu = new JMenu();
		aboutAppMenuItem = new JMenuItem();
		mainSplitPane = new JSplitPane();
		panel1 = new JPanel();
		monthView = new JXMonthView();
		mainTabbedPane = new JTabbedPane();
		closeAppAction = new CloseAppAction();
		aboutAppAction = new AboutAppAction();
		workTypesDialogAction = new WorkTypesDialogAction();
		projectsDialogAction = new ProjectsDialogAction();
		optionsAction = new OptionsAction();

		//======== this ========
		setTitle(bundle.getString("Timeticker.Title"));
		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				thisWindowClosing(e);
			}

      public void windowIconified(WindowEvent e) {
        hideWindow();
      }
    });
		Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		//======== menuBar1 ========
		{

			//======== timeTickerMenu ========
			{
				timeTickerMenu.setText(bundle.getString("MainWindow.MainMeny.TimeTicker.Title"));

				//---- closeAppMenuItem ----
				closeAppMenuItem.setText("text");
				closeAppMenuItem.setAction(closeAppAction);
				timeTickerMenu.add(closeAppMenuItem);
			}
			menuBar1.add(timeTickerMenu);

			//======== viewMenu ========
			{
				viewMenu.setText(bundle.getString("MainWindow.MainMenu.View.Title"));

				//======== languageMenu ========
				{
					languageMenu.setText(bundle.getString("MainWindow.LanguageMenu.Title"));
				}
				viewMenu.add(languageMenu);
				viewMenu.addSeparator();

				//---- projectsMenuItem ----
				projectsMenuItem.setText("text");
				projectsMenuItem.setAction(projectsDialogAction);
				viewMenu.add(projectsMenuItem);

				//---- workTypesMenuItem ----
				workTypesMenuItem.setText("text");
				workTypesMenuItem.setAction(workTypesDialogAction);
				viewMenu.add(workTypesMenuItem);
				viewMenu.addSeparator();

				//---- menuItem3 ----
				menuItem3.setText("text");
				menuItem3.setAction(optionsAction);
				viewMenu.add(menuItem3);
			}
			menuBar1.add(viewMenu);

			//======== helpMenu ========
			{
				helpMenu.setText(bundle.getString("MainWindow.MainMenu.Help.Title"));

				//---- aboutAppMenuItem ----
				aboutAppMenuItem.setText("text");
				aboutAppMenuItem.setAction(aboutAppAction);
				helpMenu.add(aboutAppMenuItem);
			}
			menuBar1.add(helpMenu);
		}
		setJMenuBar(menuBar1);

		//======== mainSplitPane ========
		{

			//======== panel1 ========
			{
				panel1.setBorder(new EmptyBorder(10, 10, 10, 10));

				// JFormDesigner evaluation mark
				panel1.setBorder(new javax.swing.border.CompoundBorder(
					new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
						"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
						javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
						java.awt.Color.red), panel1.getBorder())); panel1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});

				panel1.setLayout(new GridBagLayout());
				((GridBagLayout)panel1.getLayout()).rowHeights = new int[] {0, 0, 0};
				((GridBagLayout)panel1.getLayout()).rowWeights = new double[] {0.0, 0.0, 1.0E-4};

				//---- monthView ----
				monthView.setTraversable(true);
				monthView.setSelectionMode(JXMonthView.SelectionMode.SINGLE_INTERVAL_SELECTION);
				monthView.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						monthViewActionPerformed(e);
					}
				});
				panel1.add(monthView, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 0), 0, 0));
			}
			mainSplitPane.setLeftComponent(panel1);
			mainSplitPane.setRightComponent(mainTabbedPane);
		}
		contentPane.add(mainSplitPane, BorderLayout.CENTER);
		pack();
		setLocationRelativeTo(null);
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	// Generated using JFormDesigner Evaluation license - Ivan Latysh
	private JMenuBar menuBar1;
	private JMenu timeTickerMenu;
	private JMenuItem closeAppMenuItem;
	private JMenu viewMenu;
	private JMenu languageMenu;
	private JMenuItem projectsMenuItem;
	private JMenuItem workTypesMenuItem;
	private JMenuItem menuItem3;
	private JMenu helpMenu;
	private JMenuItem aboutAppMenuItem;
	private JSplitPane mainSplitPane;
	private JPanel panel1;
	private JXMonthView monthView;
	private JTabbedPane mainTabbedPane;
	private CloseAppAction closeAppAction;
	private AboutAppAction aboutAppAction;
	private WorkTypesDialogAction workTypesDialogAction;
	private ProjectsDialogAction projectsDialogAction;
	private OptionsAction optionsAction;
  // JFormDesigner - End of variables declaration  //GEN-END:variables

	private class CloseAppAction extends AbstractAction {
		private CloseAppAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("MainWindow.CloseAppAction.Title"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      // @TODO persist window geometry
      // close the window
      MainWindow.this.setVisible(false);
      // destroy the window      
      MainWindow.this.dispose();
      // detach form TimeTicker
      Timekeeper.getInstance().removeListener(MainWindow.this);
      // destroy application
      Main.main.detroyApplication();
		}
	}

	private class AboutAppAction extends AbstractAction {
		private AboutAppAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("MainWindow.AboutAppAction.Title"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
			JOptionPane.showMessageDialog(MainWindow.this, "TimeTicker v0.1");
		}
	}

	private class WorkTypesDialogAction extends AbstractAction {
		private WorkTypesDialogAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("MainWindow.WorkTypesAction.Title"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      // create work types dialog
      WorkTypesDialog wtypes = new WorkTypesDialog(MainWindow.this);
      // show dialog
      wtypes.setVisible(true);
      // dispose dialog
      wtypes.dispose();
		}
	}

	private class ProjectsDialogAction extends AbstractAction {
		private ProjectsDialogAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("MainWindow.ProjectsAction.Title"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      // create projects dialog
      ProjectsDialog projects = new ProjectsDialog(MainWindow.this);
      // show dialog
      projects.setVisible(true);
      // dispose dialog
      projects.dispose();
		}
	}

	private class OptionsAction extends AbstractAction {
		private OptionsAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("MainWindow.OptionsAction.Title"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
			// 
		}
	}

	private class LoadActivitiesAction extends AbstractAction {
		private LoadActivitiesAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      DayRange range = null;
      ActivityList act = null;
      try {
        // Get selected date
        SortedSet<Date> monthViewSelection = ((JXMonthView) e.getSource()).getSelection();
        range = new DayRange(monthViewSelection.first(), monthViewSelection.last());
        // check date
        SimpleDateFormat compateFormat = new SimpleDateFormat("yyyyDD");
        // load activities
        Timekeeper timekeeper = Timekeeper.getInstance();
        // load activities only when range has been changed
        if (!range.equals(timekeeper.getActivityList().getDateRange())) timekeeper.loadActivityList(range);
      } catch (Exception ex) {
        logger.error("[MWD00001] Unable to load activity list for {"+ range +"}", ex);
      }
		}
	}

	private class ToggleLanguageAction extends AbstractAction {
		private ToggleLanguageAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
			// TODO add your code here
		}
	}
}
